import React, { useState, useEffect } from 'react';
import {
  Box,
  Paper,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Button,
  Checkbox,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Typography,
  Alert,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  CircularProgress,
  Chip,
  IconButton,
  Tooltip,
  TablePagination,
  Avatar
} from '@mui/material';
import {
  Delete as DeleteIcon,
  Folder as FolderIcon,
  Image as ImageIcon,
  DeleteSweep as DeleteSweepIcon,
  Refresh as RefreshIcon,
  Visibility as VisibilityIcon,
  Close as CloseIcon,
  CloudUpload as CloudUploadIcon
} from '@mui/icons-material';
import { api, ImageFile, Folder } from '../../request';

interface FileItem extends ImageFile {
  real_path?: string;
}

const FileManagement: React.FC = () => {
  const [folders, setFolders] = useState<Folder[]>([]);
  const [files, setFiles] = useState<FileItem[]>([]);
  const [selectedFolder, setSelectedFolder] = useState<string>('');
  const [selectedFiles, setSelectedFiles] = useState<string[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [deleteAllDialogOpen, setDeleteAllDialogOpen] = useState(false);
  const [deleteType, setDeleteType] = useState<'single' | 'batch' | 'all'>('single');
  const [targetFile, setTargetFile] = useState<string>('');
  
  // 分页相关状态
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(10);
  const [totalFiles, setTotalFiles] = useState(0);
  
  // 图片预览相关状态
  const [previewDialogOpen, setPreviewDialogOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState<FileItem | null>(null);
  
  // 文件上传相关状态
  const [uploadDialogOpen, setUploadDialogOpen] = useState(false);
  const [uploadFiles, setUploadFiles] = useState<File[]>([]);
  const [uploading, setUploading] = useState(false);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [uploadResults, setUploadResults] = useState<{success: number, failed: number}>({success: 0, failed: 0});

  // 加载文件夹列表
  const loadFolders = async () => {
    try {
      setLoading(true);
      setError(null);
      const response = await api.getFolders();
      if (response.success) {
        setFolders(response.folders);
      } else {
        setError(response.message || '获取文件夹列表失败');
      }
    } catch (err) {
      setError(`获取文件夹列表失败: ${err}`);
    } finally {
      setLoading(false);
    }
  };

  // 加载指定文件夹下的文件
  const loadFiles = async (folderPath: string, pageNum: number = 1) => {
    if (!folderPath) {
      setFiles([]);
      setTotalFiles(0);
      return;
    }

    try {
      setLoading(true);
      setError(null);
      const response = await api.getImages(folderPath, pageNum, rowsPerPage);
      if (response.success) {
        setFiles(response.images);
        setTotalFiles(response.pagination?.total || response.images.length);
      } else {
        setError(response.message || '获取文件列表失败');
      }
    } catch (err) {
      setError(`获取文件列表失败: ${err}`);
    } finally {
      setLoading(false);
    }
  };

  // 处理分页变化
  const handlePageChange = (event: unknown, newPage: number) => {
    setPage(newPage);
    loadFiles(selectedFolder, newPage + 1);
  };

  const handleRowsPerPageChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const newRowsPerPage = parseInt(event.target.value, 10);
    setRowsPerPage(newRowsPerPage);
    setPage(0);
    loadFiles(selectedFolder, 1);
  };

  // 处理图片预览
  const handlePreviewImage = (file: FileItem) => {
    setPreviewImage(file);
    setPreviewDialogOpen(true);
  };

  // 获取缩略图URL
  const getThumbnailUrl = (file: FileItem) => {
    return api.getThumbnailUrl(file.path, 'small');
  };

  // 获取完整图片URL
  const getFullImageUrl = (file: FileItem) => {
    return `/api/download?path=${encodeURIComponent(file.real_path || file.path)}`;
  };

  // 处理文件夹选择
  const handleFolderChange = (folderPath: string) => {
    setSelectedFolder(folderPath);
    setSelectedFiles([]);
    setPage(0);
    loadFiles(folderPath, 1);
  };

  // 处理文件选择
  const handleFileSelect = (filePath: string, checked: boolean) => {
    if (checked) {
      setSelectedFiles(prev => [...prev, filePath]);
    } else {
      setSelectedFiles(prev => prev.filter(path => path !== filePath));
    }
  };

  // 全选/取消全选
  const handleSelectAll = (checked: boolean) => {
    if (checked) {
      setSelectedFiles(files.map(file => file.path));
    } else {
      setSelectedFiles([]);
    }
  };

  // 删除单个文件
  const handleDeleteSingle = (filePath: string, fileName: string) => {
    setTargetFile(fileName);
    setDeleteType('single');
    setDeleteDialogOpen(true);
  };

  // 批量删除
  const handleDeleteBatch = () => {
    if (selectedFiles.length === 0) {
      setError('请先选择要删除的文件');
      return;
    }
    setDeleteType('batch');
    setDeleteDialogOpen(true);
  };

  // 删除文件夹所有照片
  const handleDeleteAll = () => {
    if (!selectedFolder) {
      setError('请先选择文件夹');
      return;
    }
    setDeleteAllDialogOpen(true);
  };

  // 确认删除
  const confirmDelete = async () => {
    try {
      setLoading(true);
      setError(null);

      if (deleteType === 'single') {
        // 删除单个文件
        const filePath = selectedFiles.length > 0 ? selectedFiles[0] : 
          files.find(f => f.name === targetFile)?.path;
        if (filePath) {
          const response = await api.deleteImage(filePath);
          if (response.success) {
            setError(null);
            loadFiles(selectedFolder, page + 1); // 重新加载文件列表
          } else {
            setError(response.message || '删除失败');
          }
        }
      } else if (deleteType === 'batch') {
        // 批量删除
        let successCount = 0;
        let failCount = 0;
        
        for (const filePath of selectedFiles) {
          try {
            const response = await api.deleteImage(filePath);
            if (response.success) {
              successCount++;
            } else {
              failCount++;
            }
          } catch {
            failCount++;
          }
        }
        
        if (failCount > 0) {
          setError(`批量删除完成：成功 ${successCount} 个，失败 ${failCount} 个`);
        } else {
          setError(null);
        }
        
        setSelectedFiles([]);
        // 检查删除后当前页是否为空，如果为空则回到上一页
        const remainingFiles = files.length - selectedFiles.length;
        const newPage = remainingFiles > 0 && remainingFiles <= page * rowsPerPage ? Math.max(0, page - 1) : page;
        setPage(newPage);
        loadFiles(selectedFolder, newPage + 1); // 重新加载文件列表
      }
    } catch (err) {
      setError(`删除操作失败: ${err}`);
    } finally {
      setLoading(false);
      setDeleteDialogOpen(false);
    }
  };

  // 确认删除文件夹所有照片
  const confirmDeleteAll = async () => {
    try {
      setLoading(true);
      setError(null);
      
      let successCount = 0;
      let failCount = 0;
      
      for (const file of files) {
        try {
          const response = await api.deleteImage(file.path);
          if (response.success) {
            successCount++;
          } else {
            failCount++;
          }
        } catch {
          failCount++;
        }
      }
      
      if (failCount > 0) {
        setError(`删除完成：成功 ${successCount} 个，失败 ${failCount} 个`);
      } else {
        setError(null);
      }
      
      setSelectedFiles([]);
      setPage(0);
      loadFiles(selectedFolder, 1); // 重新加载文件列表
    } catch (err) {
      setError(`删除操作失败: ${err}`);
    } finally {
      setLoading(false);
      setDeleteAllDialogOpen(false);
    }
  };

  // 处理上传文件选择
  const handleUploadFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(event.target.files || []);
    if (files.length > 0) {
      // 检查文件类型
      const invalidFiles = files.filter(file => !file.type.startsWith('image/'));
      if (invalidFiles.length > 0) {
        setError('请只选择图片文件');
        return;
      }
      setUploadFiles(files);
      setUploadDialogOpen(true);
    }
  };

  // 上传文件
  const handleUpload = async () => {
    if (!uploadFiles.length || !selectedFolder) {
      setError('请选择文件和目标文件夹');
      return;
    }

    try {
      setUploading(true);
      setError(null);
      setUploadProgress(0);
      setUploadResults({success: 0, failed: 0});

      let successCount = 0;
      let failedCount = 0;
      const totalFiles = uploadFiles.length;

      for (let i = 0; i < uploadFiles.length; i++) {
        const file = uploadFiles[i];
        try {
          const response = await api.uploadFile(file, selectedFolder, true, false);
          
          if (response.success) {
            successCount++;
          } else {
            failedCount++;
          }
        } catch (err) {
          failedCount++;
        }
        
        // 更新进度
        setUploadProgress(Math.round(((i + 1) / totalFiles) * 100));
        setUploadResults({success: successCount, failed: failedCount});
      }
      
      if (failedCount > 0) {
        setError(`上传完成：成功 ${successCount} 个，失败 ${failedCount} 个`);
      } else {
        setError(null);
      }
      
      // 延迟关闭对话框，让用户看到结果
      setTimeout(() => {
        setUploadDialogOpen(false);
        setUploadFiles([]);
        // 重新加载文件列表
        loadFiles(selectedFolder, page + 1);
      }, 2000);
      
    } catch (err) {
      setError(`上传失败: ${err}`);
    } finally {
      setUploading(false);
    }
  };

  // 取消上传
  const handleCancelUpload = () => {
    setUploadDialogOpen(false);
    setUploadFiles([]);
    setUploadProgress(0);
    setUploadResults({success: 0, failed: 0});
  };

  // 格式化文件大小
  const formatFileSize = (size: string) => {
    return size;
  };

  // 格式化时间
  const formatTime = (time: string) => {
    return time;
  };

  useEffect(() => {
    loadFolders();
  }, []);

  return (
    <Box sx={{ p: 3 }}>
      <Typography variant="h4" gutterBottom>
        文件管理
      </Typography>

      {error && (
        <Alert severity="error" sx={{ mb: 2 }} onClose={() => setError(null)}>
          {error}
        </Alert>
      )}

      {/* 文件夹选择 */}
      <Box sx={{ mb: 3, display: 'flex', alignItems: 'center', gap: 2 }}>
        <FormControl sx={{ minWidth: 200 }}>
          <InputLabel>选择文件夹</InputLabel>
          <Select
            value={selectedFolder}
            label="选择文件夹"
            onChange={(e) => handleFolderChange(e.target.value)}
          >
            <MenuItem value="">
              <em>请选择文件夹</em>
            </MenuItem>
            {folders.map((folder) => (
              <MenuItem key={folder.path} value={folder.path}>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                  <FolderIcon fontSize="small" />
                  {folder.name}
                </Box>
              </MenuItem>
            ))}
          </Select>
        </FormControl>

        <Tooltip title="刷新">
          <IconButton onClick={loadFolders} disabled={loading}>
            <RefreshIcon />
          </IconButton>
        </Tooltip>
      </Box>

      {/* 操作按钮 */}
      {selectedFolder && (
        <Box sx={{ mb: 2, display: 'flex', gap: 2, alignItems: 'center' }}>
          <input
            accept="image/*"
            style={{ display: 'none' }}
            id="upload-file-input"
            type="file"
            multiple
            onChange={handleUploadFileSelect}
          />
          <label htmlFor="upload-file-input">
            <Button
              variant="contained"
              color="primary"
              component="span"
              startIcon={<CloudUploadIcon />}
              disabled={loading || uploading}
            >
              上传图片
            </Button>
          </label>
          <Button
            variant="contained"
            color="error"
            startIcon={<DeleteIcon />}
            onClick={handleDeleteBatch}
            disabled={selectedFiles.length === 0 || loading}
          >
            批量删除 ({selectedFiles.length})
          </Button>
          <Button
            variant="outlined"
            color="error"
            startIcon={<DeleteSweepIcon />}
            onClick={handleDeleteAll}
            disabled={files.length === 0 || loading}
          >
            删除文件夹所有照片 ({files.length})
          </Button>
        </Box>
      )}

      {/* 文件列表表格 */}
      {selectedFolder && (
        <TableContainer component={Paper}>
          <Table>
            <TableHead>
              <TableRow>
                <TableCell padding="checkbox">
                  <Checkbox
                    indeterminate={selectedFiles.length > 0 && selectedFiles.length < files.length}
                    checked={files.length > 0 && selectedFiles.length === files.length}
                    onChange={(e) => handleSelectAll(e.target.checked)}
                    disabled={loading}
                  />
                </TableCell>
                <TableCell>缩略图</TableCell>
                <TableCell>文件名</TableCell>
                <TableCell>类型</TableCell>
                <TableCell>大小</TableCell>
                <TableCell>修改时间</TableCell>
                <TableCell>操作</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {loading ? (
                <TableRow>
                  <TableCell colSpan={6} align="center">
                    <CircularProgress size={24} />
                    <Typography variant="body2" sx={{ ml: 1 }}>加载中...</Typography>
                  </TableCell>
                </TableRow>
              ) : files.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={6} align="center">
                    <Typography variant="body2" color="text.secondary">
                      该文件夹下没有图片文件
                    </Typography>
                  </TableCell>
                </TableRow>
              ) : (
                files.map((file) => (
                  <TableRow key={file.path} hover>
                    <TableCell padding="checkbox">
                      <Checkbox
                        checked={selectedFiles.includes(file.path)}
                        onChange={(e) => handleFileSelect(file.path, e.target.checked)}
                        disabled={loading}
                      />
                    </TableCell>
                    <TableCell>
                      <Avatar
                        src={getThumbnailUrl(file)}
                        alt={file.name}
                        variant="rounded"
                        sx={{ width: 50, height: 50, cursor: 'pointer' }}
                        onClick={() => handlePreviewImage(file)}
                      >
                        <ImageIcon />
                      </Avatar>
                    </TableCell>
                    <TableCell>
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                        <ImageIcon fontSize="small" color="primary" />
                        {file.name}
                      </Box>
                    </TableCell>
                    <TableCell>
                      <Chip label="图片" size="small" color="primary" variant="outlined" />
                    </TableCell>
                    <TableCell>{formatFileSize(file.size)}</TableCell>
                    <TableCell>{formatTime(file.mtime)}</TableCell>
                    <TableCell>
                      <Box sx={{ display: 'flex', gap: 1 }}>
                        <Tooltip title="预览">
                          <IconButton
                            size="small"
                            color="primary"
                            onClick={() => handlePreviewImage(file)}
                            disabled={loading}
                          >
                            <VisibilityIcon fontSize="small" />
                          </IconButton>
                        </Tooltip>
                        <Tooltip title="删除">
                          <IconButton
                            size="small"
                            color="error"
                            onClick={() => handleDeleteSingle(file.path, file.name)}
                            disabled={loading}
                          >
                            <DeleteIcon fontSize="small" />
                          </IconButton>
                        </Tooltip>
                      </Box>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
          {/* 分页组件 */}
          <TablePagination
            component="div"
            count={totalFiles}
            page={page}
            onPageChange={handlePageChange}
            rowsPerPage={rowsPerPage}
            onRowsPerPageChange={handleRowsPerPageChange}
            rowsPerPageOptions={[5, 10, 25, 50]}
            labelRowsPerPage="每页显示："
            labelDisplayedRows={({ from, to, count }) => `${from}-${to} 共 ${count !== -1 ? count : `超过 ${to}`} 条`}
          />
        </TableContainer>
      )}

      {/* 删除确认对话框 */}
      <Dialog open={deleteDialogOpen} onClose={() => setDeleteDialogOpen(false)}>
        <DialogTitle>
          {deleteType === 'single' ? '确认删除文件' : '确认批量删除'}
        </DialogTitle>
        <DialogContent>
          <Typography>
            {deleteType === 'single'
              ? `确定要删除文件 "${targetFile}" 吗？`
              : `确定要删除选中的 ${selectedFiles.length} 个文件吗？`}
          </Typography>
          <Typography variant="body2" color="error" sx={{ mt: 1 }}>
            此操作不可撤销！
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDeleteDialogOpen(false)} disabled={loading}>
            取消
          </Button>
          <Button onClick={confirmDelete} color="error" disabled={loading}>
            {loading ? <CircularProgress size={20} /> : '确认删除'}
          </Button>
        </DialogActions>
      </Dialog>

      {/* 删除文件夹所有照片确认对话框 */}
      <Dialog open={deleteAllDialogOpen} onClose={() => setDeleteAllDialogOpen(false)}>
        <DialogTitle>确认删除文件夹所有照片</DialogTitle>
        <DialogContent>
          <Typography>
            确定要删除文件夹 "{folders.find(f => f.path === selectedFolder)?.name}" 下的所有 {files.length} 张照片吗？
          </Typography>
          <Typography variant="body2" color="error" sx={{ mt: 1 }}>
            此操作不可撤销！
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDeleteAllDialogOpen(false)} disabled={loading}>
            取消
          </Button>
          <Button onClick={confirmDeleteAll} color="error" disabled={loading}>
            {loading ? <CircularProgress size={20} /> : '确认删除全部'}
          </Button>
        </DialogActions>
      </Dialog>

      {/* 上传确认对话框 */}
      <Dialog open={uploadDialogOpen} onClose={handleCancelUpload}>
        <DialogTitle>上传图片</DialogTitle>
        <DialogContent>
          {uploadFiles.length > 0 && (
            <Box>
              <Typography variant="body1" gutterBottom>
                选择了 {uploadFiles.length} 个文件
              </Typography>
              <Typography variant="body2" color="text.secondary" gutterBottom>
                总大小: {(uploadFiles.reduce((sum, file) => sum + file.size, 0) / 1024 / 1024).toFixed(2)} MB
              </Typography>
              <Typography variant="body2" color="text.secondary" gutterBottom>
                目标文件夹: {folders.find(f => f.path === selectedFolder)?.name}
              </Typography>
              {uploading && (
                <Box sx={{ mt: 2 }}>
                  <Typography variant="body2" gutterBottom>
                    上传进度: {uploadProgress}% (成功: {uploadResults.success}, 失败: {uploadResults.failed})
                  </Typography>
                  <CircularProgress variant="determinate" value={uploadProgress} />
                </Box>
              )}
            </Box>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCancelUpload} disabled={uploading}>
            取消
          </Button>
          <Button onClick={handleUpload} color="primary" disabled={uploading}>
            {uploading ? '上传中...' : '确认上传'}
          </Button>
        </DialogActions>
      </Dialog>

      {/* 图片预览对话框 */}
      <Dialog
        open={previewDialogOpen}
        onClose={() => setPreviewDialogOpen(false)}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>
          <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <Typography variant="h6">
              {previewImage?.name}
            </Typography>
            <IconButton onClick={() => setPreviewDialogOpen(false)}>
               <CloseIcon />
             </IconButton>
          </Box>
        </DialogTitle>
        <DialogContent>
          {previewImage && (
            <Box sx={{ textAlign: 'center' }}>
              <img
                src={getFullImageUrl(previewImage)}
                alt={previewImage.name}
                style={{
                  maxWidth: '100%',
                  maxHeight: '70vh',
                  objectFit: 'contain'
                }}
                onError={(e) => {
                  const target = e.target as HTMLImageElement;
                  target.src = getThumbnailUrl(previewImage);
                }}
              />
              <Box sx={{ mt: 2, display: 'flex', justifyContent: 'space-around', textAlign: 'left' }}>
                <Typography variant="body2">
                  <strong>大小:</strong> {formatFileSize(previewImage.size)}
                </Typography>
                <Typography variant="body2">
                  <strong>修改时间:</strong> {formatTime(previewImage.mtime)}
                </Typography>
              </Box>
            </Box>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setPreviewDialogOpen(false)}>
            关闭
          </Button>
          {previewImage && (
            <Button
              color="error"
              onClick={() => {
                setPreviewDialogOpen(false);
                handleDeleteSingle(previewImage.path, previewImage.name);
              }}
            >
              删除此图片
            </Button>
          )}
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default FileManagement;